﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpenseSystem.Model;
using ExpenseSystem.Lor;
using ExpenseSystem.Common;
using ExpenseSystem.DataUpdater;
using ExpenseSystem.Fether;
using ExpenseSystem.DataUpdater.Validation;

namespace ExpenseSystem.Core.ProductionModules
{
    public class UnitGroupUpdaterRegister
    {
        int rows;
        public NormalDataUpdater<UnitGroupModel> GetUnitGroupUpdater()
        {
            NormalDataUpdater<UnitGroupModel> systemDataUpdater = new NormalDataUpdater<UnitGroupModel>();
            systemDataUpdater.DataUpdating += DataNotSpaceValid;
            systemDataUpdater.DataUpdating += SingletonValid;
            systemDataUpdater.DataDeleting += CheckAvaliable;
            return systemDataUpdater;
        }
        private void CheckAvaliable(object sender, DataValidationEventArgs<UnitGroupModel> e)
        {
            string message;
            ProductionFetcher productionFetcher = new ProductionFetcher();
            IList<ProductionModel> result = productionFetcher.List(e.Delete.Site, OrderBy.GetDefault(), Limit.GetDefault(), out message, out rows, Restrain.Eq("UnitGroupId", e.Delete.AutoId));
            if (result.Count > 0)
            {
                e.Cancle = true;
                message = "本档案已被使用";
                return;
            }
            UnitFetcher unitFetcher = new UnitFetcher();
            if(unitFetcher.ListByMainId(e.Delete.Site,e.Delete.AutoId,out message, out rows).Count>0)
            {
                e.Cancle = true;
                message = "本档案已被使用";
                return;
            }
        }

        private void SingletonValid(object sender, DataValidationEventArgs<UnitGroupModel> e)
        {
            UnitGroupFetcher roleFetcher = new UnitGroupFetcher();
            string message = "";
            UnitGroupModel role = roleFetcher.GetByCode(e.Insert.Site, e.Insert.Code,out message);
            if (role != null && role.AutoId != e.Insert.AutoId)
            {
                e.Cancle = true;
                message = String.Format("代号[{0}]已被[{1}]占用", role.Code, role.Name);
                return;
            }
        }

        private void DataNotSpaceValid(object sender, DataValidationEventArgs<UnitGroupModel> e)
        {
            if (String.IsNullOrWhiteSpace(e.Insert.Code))
            {
                e.Message = "代号不能为空";
                e.Cancle = true;
                return;
            }
            if (String.IsNullOrWhiteSpace(e.Insert.Name))
            {
                e.Message = "名称不能为空";
                e.Cancle = true;
                return;
            }
        }
    }
}
